package com.bl.student.manager.controller;

import com.bl.student.common.ApiResponseBody;
import com.bl.student.common.utils.CommonUtils;
import com.bl.student.service.biz.manager.main.ManageMainService;
import com.bl.student.service.biz.teacher.TeacherMainService;
import com.bl.student.service.vo.manager.ManageLoginResponseVo;
import com.bl.student.service.vo.manager.ManageLoginVo;
import com.google.common.base.Optional;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

/**
 * Created by yujingyi on 2018/1/21.
 */
@RestController
@Log4j2
@RequestMapping(value = {"/student/manager"})
@Api(value = "注册登陆相关api", description = "注册登陆相关api")
public class MainController extends BaseController {

    @Autowired
    ManageMainService manageMainService;


    @ApiOperation(value = "用户登陆接口", notes = "用户登陆接口")
    @PostMapping(value = {"/login"})
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public ApiResponseBody<ManageLoginResponseVo> login(
            @Valid @RequestBody ManageLoginVo body, BindingResult result,
            HttpServletRequest request, HttpServletResponse response) {

        ApiResponseBody validResult = validParams(result);
        if (validResult != null) {
            return validResult;
        }

        ManageLoginResponseVo manageLoginResponseVo = manageMainService.login(body);

        // logout pre user if exist
        Optional<Cookie> cookieOptional = getCookie(request, CommonUtils.ADMIN_TOKEN_KEY);
        if (cookieOptional.isPresent()) {
            manageMainService.logout(cookieOptional.get().getValue());
        }

        // set cookie
        Cookie tokenCookie = new Cookie(CommonUtils.ADMIN_TOKEN_KEY, manageLoginResponseVo.getToken());
        tokenCookie.setPath("/");
        tokenCookie.setMaxAge(3600 * 24 * 30);

        response.addCookie(tokenCookie);

        return ApiResponseBody.createSuccessBody(manageLoginResponseVo);
    }
}
